import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:crypto/crypto.dart';

class HeaderInterceptor extends Interceptor {
  late String appId;
  late String appkey;
  String nonceStr = "ssBbeJEy1aQlZhE4KqUQ";
  DateTime now = DateTime.now();

  HeaderInterceptor() {
    appId = "meiyunAdmin";
    appkey = "meiyunAdmin20210603UjnrUaGRZYAvL44ajuDqmR56IIIC";
  }

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    //super.onRequest(options, handler);
    num timestamp = now.millisecondsSinceEpoch;
    String value =
        "appId=$appId&nonceStr=$nonceStr&timestamp=$timestamp$appkey";

    String sign = generateMd5(value).toUpperCase();

    Map<String, dynamic> head = options.headers;
    head["appId"] = appId;
    head["nonceStr"] = nonceStr;
    head["timestamp"] = timestamp;
    head["sign"] = sign;

    handler.next(options);
  }

  String generateMd5(String data) {
    var content = const Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return digest.toString();
  }
}
